<template>
  <div class="app-container">
    <div class="content-block">
      <el-form-item label="店铺">
        <el-select v-model="currentMall" placeholder="请选择 店铺" clearable>
          <el-option
            v-for="item in mallList"
            :key="item.mallId"
            :label="item.mallName"
            :value="item.mallId + ''"
          />
        </el-select>
      </el-form-item>
    </div>
    <div class="content-block">
      <div class="bar-title">关键指标</div>
      <div class="flex-r-b-center top-bar">
        <el-radio-group v-model="countType" size="small">
          <el-radio-button :label="1">今天</el-radio-button>
          <el-radio-button :label="7">近7天</el-radio-button>
          <el-radio-button :label="30">近30天</el-radio-button>
          <el-radio-button :label="60">近60天</el-radio-button>
          <el-radio-button :label="180">近180天</el-radio-button>
        </el-radio-group>
        <div>统计时间：{{ countDate }}</div>
      </div>
      <div class="series-block">
        <div v-for="s in seriesList" :key="s.label" class="s-item">
          <div class="flex-r-b-center">
            <div class="flex-r-y-center flex-1 s-label">
              <span style="padding-right: 4px">{{ s.label }}</span>
              <el-popover
                placement="top"
                :width="300"
                trigger="hover"
                :content="s.tip"
              >
                <template #reference>
                  <el-icon><QuestionFilled /></el-icon>
                </template>
              </el-popover>
            </div>
          </div>
          <p class="s-value">{{ s.value }}</p>
          <p class="seven-data">
            <!--近7天日均变化 <span>{{ 16.25 }}%</span>-->
          </p>
        </div>
      </div>
      <ChartView ref="chartRef" :config="config" />
    </div>
    <div class="content-block">
      <div class="bar-title">
        <p>
          <span>TOP 10 商品排行榜</span>
          <!--<span class="sub-title">统计时间: 2023-01-01 ~ 2023-02-02</span>-->
        </p>
        <!--<el-button type="primary" link>-->
        <!--  更多<el-icon><ArrowRight /></el-icon>-->
        <!--</el-button>-->
      </div>
      <el-table
        :data="top10Data"
        highlight-current-row
        :header-cell-style="{
          background: '#eef0f1',
          color: '#333'
        }"
      >
        <el-table-column type="index" label="排名" width="100" />
        <el-table-column prop="productName" label="商品信息">
          <template v-slot="{ row }">
            <div class="product-block">
              <img :src="row.productSkcPicture" alt="product" />
              <div>
                <span>商品名称: {{ row.productName }}</span>
                <span>SPU: {{ row.productId }}</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="lastThirtyDaysSaleVolume"
          width="200"
          label="近30天销量"
        />
        <el-table-column prop="inCartNumber7d" width="200" label="7日加购数" />
        <el-table-column prop="warehouseAvailableSaleDays" width="200">
          <template #header="{ column }">
            {{ '仓内库存可售天数' }}
            <el-popover
              placement="top"
              :width="300"
              trigger="hover"
              content="仓内库存可售天数 =（仓内可用库存 - 缺货数量） / 近7天日销量"
            >
              <template #reference>
                <el-icon><QuestionFilled /></el-icon>
              </template>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, nextTick } from 'vue'
import { QuestionFilled, ArrowRight, CaretTop } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import ChartView from '@/components/ChartView/index.vue'
import { todayTemuShopTotalInfoHistory, top10 } from '@/api/chart'
import { useUserStore } from '@/store/user'

const countType = ref(1)
const countDate = computed(() => {
  switch (countType.value) {
    case 1:
      return dayjs().subtract(1, 'day').format('YYYY-MM-DD')
    default:
      return `${dayjs()
        .subtract(countType.value + 1, 'day')
        .format('YYYY-MM-DD')} ~ ${dayjs()
        // .startOf('day')
        .subtract(1, 'day')
        .format('YYYY-MM-DD')}`
  }
})
const currentMall = ref('')
const seriesList = ref([
  {
    label: '销量',
    value: 0,
    tip: '统计期间内，客户支付成功的件数。含支付后取消或退款的销量'
  },
  {
    label: '在售SKC数',
    value: 0,
    tip: '统计期间内，曾可售的SKC数'
  },
  {
    label: '销售额',
    value: 0,
    tip: ''
  },
  {
    label: '评论数',
    value: 0,
    tip: ''
  }
])
const chartRef = ref(null)
const configData = ref([])
const config = computed(() => {
  const xAxisData = []
  let series = [
    {
      name: '销量',
      type: 'line',
      data: []
    },
    {
      name: '在售skc数',
      type: 'line',
      data: []
    },
    {
      name: '销售额',
      type: 'line',
      data: []
    },
    {
      name: '评论数',
      type: 'line',
      data: []
    }
  ]

  if (Array.isArray(configData.value) && configData.value.length) {
    configData.value.forEach((item) => {
      xAxisData.push(item.date)
      series[0].data.push(item.todaySaleVolme)
      series[1].data.push(item.todaySaledSkcNum)
      series[2].data.push(item.todaySalePrice)
      series[3].data.push(item.commentNum)
    })
  }

  return {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['销量', '在售skc数', '销售额', '评论数']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: xAxisData
    },
    yAxis: {
      type: 'value'
    },
    series
  }
})
const top10Data = ref([])

const userStore = useUserStore()
const mallList = computed(() => {
  if (userStore.userInfo?.companyList && userStore.userInfo?.companyList[0]) {
    return userStore.userInfo.companyList[0].malInfoList
  } else {
    return []
  }
})

const getSaleData = async () => {
  const { temuShopTotalInfoHistory, temuShopTotalInfoTotal } =
    await todayTemuShopTotalInfoHistory({
      recentDays: countType.value,
      mallId: currentMall.value
    })
  configData.value = temuShopTotalInfoHistory
  seriesList.value[0].value = temuShopTotalInfoTotal.saleVolumeTotal
  seriesList.value[1].value = temuShopTotalInfoTotal.saledSkcNumAverage
  seriesList.value[2].value = temuShopTotalInfoTotal.salePriceTotal
  seriesList.value[3].value = temuShopTotalInfoTotal.commentNum
}
const getMallTop10 = async () => {
  const { result } = await top10({ mallId: currentMall.value })
  top10Data.value = result
}

watch([() => countType.value, () => currentMall.value], () => {
  if (countType.value && currentMall.value) {
    getSaleData()
    getMallTop10()
  }
})
watch(
  () => config.value,
  (config) => {
    nextTick(() => {
      chartRef.value.getChartEl().setOption(config)
    })
  }
)

onMounted(() => {
  currentMall.value = `${mallList.value?.[0].mallId}`
})
</script>

<style scoped lang="scss">
.flex-r-b-center {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-content: center;
}
.flex-r-y-center {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  align-content: center;
}
.flex-1 {
  flex: 1;
}

.content-block {
  margin-bottom: 20px;
  .bar-title {
    line-height: 26px;
    font-weight: 600;
    font-size: 18px;
    margin-bottom: 15px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .sub-title {
      color: #666c7c;
      font-size: 13px;
      font-weight: normal;
      padding-left: 6px;
    }
  }
}

.app-container {
  margin: 20px;
  padding: 20px;
  background-color: #fff;
  .top-bar {
    margin-bottom: 20px;
    > div {
      color: #666c7c;
      font-size: 13px;
    }
  }
  .series-block {
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 30px;
    .s-item {
      width: 25%;
      padding: 12px;
      border: solid 1px #e3e3e3;
      margin-left: -1px;
      .s-label {
        font-size: 14px;
        color: #5a5e66;
        svg {
          cursor: pointer;
        }
      }
      .s-value {
        padding-top: 8px;
        font-size: 26px;
        font-weight: bold;
      }
      .seven-data {
        margin-top: 6px;
        color: #5a5e66;
        font-size: 12px;
        > span {
          color: #67c23a;
        }
      }
    }
  }
  .product-block {
    display: flex;
    > img {
      width: 80px;
    }
    > div {
      padding-left: 10px;
      display: flex;
      flex-direction: column;
      span:nth-of-type(1) {
        font-size: 16px;
        margin-bottom: 6px;
      }
      span:nth-of-type(2) {
        color: #bdbdbd;
        font-size: 14px;
      }
    }
  }
}
</style>
